package org.kernely.stream;

import java.util.Dictionary;
import java.util.Hashtable;

import org.kernely.core.service.BundlePresentService;
import org.kernely.stream.messageFilter.LinkFilter;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.osgi.service.http.HttpService;

public class Activator implements BundleActivator, BundleListener {
	private BundleContext context;

	/**
	 * Called when the bundle is STARTING
	 */
	public void start(BundleContext pBundleContext) throws Exception {
		this.context = pBundleContext;

		// Register images
		ServiceReference sRef = pBundleContext.getServiceReference(HttpService.class.getName());
		if (sRef != null)
		{
			HttpService service = (HttpService) pBundleContext.getService(sRef);
			service.registerResources("/streambundle/images", "img", null);
		}

		// Choose topics to listen
		String[] topics = new String[] {
				"org/kernely/*"
		};
		Dictionary props = new Hashtable();
		props.put(EventConstants.EVENT_TOPIC, topics);

		// Register event handler
		pBundleContext.registerService(EventHandler.class.getName(), new StreamEventsHandler() , props);
		
		// Add this as a bundle listener
		pBundleContext.addBundleListener(this);
		
		
	}

	/**
	 * Called when the Bundle is STOPPING
	 */
	public void stop(BundleContext arg0) throws Exception {

	}

	/**
	 * Method called when a bundle's state change
	 */
	public final void bundleChanged(BundleEvent event) {
		// Retrieve the event
		Bundle bundle = event.getBundle();
		try{
			KernelyStreamServiceImpl.bundleStateChanged(bundle.getSymbolicName(), event.getType());
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
